using System;
using System.Collections.Generic;
using System.Linq;
using Sustainalytics.Entities;
using Sustainalytics.Synchronization.Validation.Entities.CorporateGovernance;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;

namespace Sustainalytics.Synchronization.Validation.ValidationRules.CorporateGovernance
{
    public class GovernanceMissingCommentsForIndicatorsWhenScoreLowerThan50Rule : Rule<GovernanceValidationProfile>
    {
        private readonly HashSet<string> indicatorsHashSet = new IndicatorsHashSet
                                                                 {
                                                                     "CG.1.8", "CG.1.9", "CG.1.10", "CG.4.4", "CG.5.6"
                                                                 };

        public override Severity Severity => Severity.Yellow;
        public override BusinessResearchProduct BusinessResearchProduct => BusinessResearchProduct.CorporateGovernance;
        public override string Code => "YR131";
        public override string InformationalMessage => "No comments for indicators when score < 50 (strictly less) (G.1.8, G.1.9, G.1.10, G.4.4, G.5.6)";

        public GovernanceMissingCommentsForIndicatorsWhenScoreLowerThan50Rule()
        {
            For(x => x.GovernanceIndicators).When(Validator).WithKey(x => x.CompanyId)
                .WithMessage("The company {0} #{1}# does not have comments for indicators G.1.8, G.1.9, G.1.10, G.4.4, G.5.6");
        }

        private bool Validator(GovernanceValidationProfile validatedEntity, GovernanceValidationProfile referenceEntity)
        {
            var indicators = (List<GovernanceIndicator>)GetValue(validatedEntity);

            if (indicators == null)
                return false;

            var triggerIndicators = indicators.Where(i => indicatorsHashSet.Contains(i.Number, StringComparer.CurrentCultureIgnoreCase) && i.Score < 50
                    && string.IsNullOrWhiteSpace(i.Comment))
                    .Select(x => x.Number);

            if (!triggerIndicators.Any())
                return true;

            SetTriggersMessages(triggerIndicators);

            return false;
        }
    }
}
